const puppeteer = require('puppeteer');
var {timeout} = require('./tools.js');

var delay = 2000;

class LoginBaiDu{
	constructor() {
		this.url = 'https://www.baidu.com/';
		this.init();
	}

	async init(){
		console.log('正在启动浏览器...');
		this.browser = await puppeteer.launch({headless:false});
		console.log('正在打开新页面...');
		this.page = await this.browser.newPage();
		await this.openBaiDu(this.url);

		console.log('正在关闭浏览器...');
		await timeout(delay);
		await this.browser.close();
	}

	async openBaiDu(url){
		await timeout(delay);
		let page = this.page;
		await page.goto(url);
		try{
			await timeout(delay);
			var login = await page.$('#u1 .lb');
			console.log('正在获取登录节点---------------'+login);
			await login.click();
			await timeout(1000);

			var userNameLogin = await page.$('#TANGRAM__PSP_10__footerULoginBtn');
			await userNameLogin.click();
			await timeout(1000)

			await page.type('[name=userName]','来生只为你心动',{delay:200});
			await timeout(500);

			await page.type('[name=password]','***',{delay:200});
			await timeout(1000)

			// 点击登录
			console.log('点击登录百度...');
			var commit = await page.$('#TANGRAM__PSP_10__submit');
			await commit.click();

			await timeout(2000)
		} catch(e){
			console.log("执行出错......."+e);
			await page.screenshot({path:'./err.png',type: 'png'});
		}
	}	

}

new LoginBaiDu();